<?php

namespace app\index\model;

use think\Model;

class Users extends Model{
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 注册表单入库
     * @param $data 表单数据
     * @return $this
     */
    public function add($data){
        //检验提交的数据是否为数组
        if(!is_array($data)){
            exception('传递的数据不是数组');
        }
        $data['status'] = 0;
        $this->data($data)->allowField(true)->save();
        return $this;
    }

    public function getUserByData($data) {
        if(!$data['username']){
            exception('用户名不合法');
        }
        //数据库查询
        $condition = [
            'username' => $data['username'],
        ];
        $user = $this->where($condition)->find();
        //判断用户是否激活
        if(!$user || $user->status == -1){
            exception('该用户不存在');
        }
        //判断密码是否正确
        if(md5($data['password'].$user->pwdcode) != $user->password){
            exception('密码错误');
        }
        //更新最后登陆ip和时间
        $this->updateById([
            'last_login_ip'=>$_SERVER["REMOTE_ADDR"],
            'last_login_time'=>time()
        ],$user->id);
        return $user;
    }

    /**
     * 根据id更新数据库数据
     * @param $data
     * @param $id
     * @return false|int
     */
    public function updateById($data,$id){
        return $this->allowField(true)->save($data,['id'=>$id]);
    }

    /**
     * 更新用户数据
     */
    public function updateData($data, $id){
        $user = $this->where(['id'=>$id])->find();
        $validate = validate('Users');//表单验证器
        if(!$validate->scene("update")->check($data)){
            exception($validate->getError());
        }
        if(!empty($data['password_current'])){
            if(!$validate->scene("changepassword")->check($data)){
                exception($validate->getError());
            }
            if(md5($data['password_current'].$user->pwdcode) != $user->password){
                exception("原密码错误！");
            }
            $data['password'] = md5($data['password'].$user['pwdcode']);
        }
        return $this->updateById($data,$id);
    }
}

